package handlers

import (
	"html/template"
	"k8s-service/models"
	"math"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 页面数据结构
type PageData struct {
	Title       string
	Message     string
	MessageType string
	Data        *models.ModelConfigListResponse
	Config      *models.ModelConfig
	Filters     FilterData
	TotalPages  int
	PageRange   []int
}

type FilterData struct {
	ModelType string
	Enabled   string
}

// 模板函数
func templateFuncs() template.FuncMap {
	return template.FuncMap{
		"sub": func(a, b int) int {
			return a - b
		},
		"add": func(a, b int) int {
			return a + b
		},
		"eq": func(a, b interface{}) bool {
			return a == b
		},
	}
}

// 渲染模板
func renderTemplate(c *gin.Context, templateName string, data PageData) {
	tmpl := template.New("layout.html").Funcs(templateFuncs())
	tmpl, err := tmpl.ParseFiles(
		"templates/layout.html",
		"templates/"+templateName+".html",
	)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "", gin.H{"error": err.Error()})
		return
	}

	c.Header("Content-Type", "text/html; charset=utf-8")
	err = tmpl.Execute(c.Writer, data)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "", gin.H{"error": err.Error()})
	}
}

// 生成页码范围
func generatePageRange(currentPage, totalPages int) []int {
	var pages []int
	start := currentPage - 2
	end := currentPage + 2

	if start < 1 {
		start = 1
	}
	if end > totalPages {
		end = totalPages
	}

	for i := start; i <= end; i++ {
		pages = append(pages, i)
	}
	return pages
}

// AdminIndex 管理后台首页 - 配置列表
func AdminIndex(c *gin.Context) {
	// 解析分页参数
	page := 1
	if pageStr := c.Query("page"); pageStr != "" {
		if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
			page = p
		}
	}

	size := 10
	if sizeStr := c.Query("size"); sizeStr != "" {
		if s, err := strconv.Atoi(sizeStr); err == nil && s > 0 && s <= 100 {
			size = s
		}
	}

	// 解析筛选参数
	modelType := c.Query("model_type")
	var enabled *int
	if enabledStr := c.Query("enabled"); enabledStr != "" {
		if e, err := strconv.Atoi(enabledStr); err == nil && (e == 0 || e == 1) {
			enabled = &e
		}
	}

	// 获取数据
	result, err := modelConfigService.ListModelConfigs(page, size, modelType, enabled)
	if err != nil {
		pageData := PageData{
			Title:       "模型配置管理",
			Message:     "获取数据失败: " + err.Error(),
			MessageType: "danger",
		}
		renderTemplate(c, "list", pageData)
		return
	}

	// 计算总页数
	totalPages := int(math.Ceil(float64(result.Total) / float64(size)))

	// 构建页面数据
	pageData := PageData{
		Title: "模型配置管理",
		Data:  result,
		Filters: FilterData{
			ModelType: modelType,
			Enabled:   c.Query("enabled"),
		},
		TotalPages: totalPages,
		PageRange:  generatePageRange(page, totalPages),
	}

	renderTemplate(c, "list", pageData)
}

// AdminCreate 显示创建表单
func AdminCreate(c *gin.Context) {
	pageData := PageData{
		Title:  "新增模型配置",
		Config: &models.ModelConfig{Enabled: 1}, // 默认启用
	}
	renderTemplate(c, "form", pageData)
}

// AdminStore 处理创建表单提交
func AdminStore(c *gin.Context) {
	var req models.CreateModelConfigRequest

	// 手动绑定表单数据
	req.ModelPath = c.PostForm("model_path")
	req.RequestHeaders = c.PostForm("request_headers")
	req.VendorCN = c.PostForm("vendor_cn")
	req.VendorEN = c.PostForm("vendor_en")

	// 处理可选的指针字段
	if vendorImg := c.PostForm("vendor_img"); vendorImg != "" {
		req.VendorImg = &vendorImg
	}
	if modelName := c.PostForm("model_name"); modelName != "" {
		req.ModelName = &modelName
	}

	req.ModelType = c.PostForm("model_type")

	enabled, _ := strconv.Atoi(c.PostForm("enabled"))
	req.Enabled = enabled

	// 创建配置
	_, err := modelConfigService.CreateModelConfig(&req)
	if err != nil {
		// 准备回显数据
		config := &models.ModelConfig{
			ModelPath:      req.ModelPath,
			RequestHeaders: req.RequestHeaders,
			VendorCN:       req.VendorCN,
			VendorEN:       req.VendorEN,
			ModelType:      req.ModelType,
			Enabled:        req.Enabled,
		}
		if req.VendorImg != nil {
			config.VendorImg = req.VendorImg
		}
		if req.ModelName != nil {
			config.ModelName = req.ModelName
		}

		pageData := PageData{
			Title:       "新增模型配置",
			Message:     "创建失败: " + err.Error(),
			MessageType: "danger",
			Config:      config,
		}
		renderTemplate(c, "form", pageData)
		return
	}

	// 清除代理缓存
	InvalidateProxyCache()

	c.Redirect(http.StatusSeeOther, "/admin?message=创建成功")
}

// AdminView 查看配置详情
func AdminView(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.Redirect(http.StatusSeeOther, "/admin?message=无效的ID&type=danger")
		return
	}

	config, err := modelConfigService.GetModelConfigByID(id)
	if err != nil {
		c.Redirect(http.StatusSeeOther, "/admin?message="+err.Error()+"&type=danger")
		return
	}

	pageData := PageData{
		Title:  "配置详情",
		Config: config,
	}
	renderTemplate(c, "view", pageData)
}

// AdminEdit 显示编辑表单
func AdminEdit(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.Redirect(http.StatusSeeOther, "/admin?message=无效的ID&type=danger")
		return
	}

	config, err := modelConfigService.GetModelConfigByID(id)
	if err != nil {
		c.Redirect(http.StatusSeeOther, "/admin?message="+err.Error()+"&type=danger")
		return
	}

	pageData := PageData{
		Title:  "编辑模型配置",
		Config: config,
	}
	renderTemplate(c, "form", pageData)
}

// AdminUpdate 处理编辑表单提交
func AdminUpdate(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.Redirect(http.StatusSeeOther, "/admin?message=无效的ID&type=danger")
		return
	}

	var req models.UpdateModelConfigRequest

	// 手动绑定表单数据
	req.ModelPath = c.PostForm("model_path")
	req.RequestHeaders = c.PostForm("request_headers")
	req.VendorCN = c.PostForm("vendor_cn")
	req.VendorEN = c.PostForm("vendor_en")

	// 处理可选的指针字段
	if vendorImg := c.PostForm("vendor_img"); vendorImg != "" {
		req.VendorImg = &vendorImg
	}
	if modelName := c.PostForm("model_name"); modelName != "" {
		req.ModelName = &modelName
	}

	req.ModelType = c.PostForm("model_type")

	enabled, _ := strconv.Atoi(c.PostForm("enabled"))
	req.Enabled = &enabled

	// 更新配置
	_, err = modelConfigService.UpdateModelConfig(id, &req)
	if err != nil {
		// 获取原配置用于表单回显
		config, _ := modelConfigService.GetModelConfigByID(id)
		if config == nil {
			config = &models.ModelConfig{}
		}

		// 使用提交的数据覆盖
		config.ModelPath = req.ModelPath
		config.RequestHeaders = req.RequestHeaders
		config.VendorCN = req.VendorCN
		config.VendorEN = req.VendorEN
		if req.VendorImg != nil {
			config.VendorImg = req.VendorImg
		}
		if req.ModelName != nil {
			config.ModelName = req.ModelName
		}
		config.ModelType = req.ModelType
		if req.Enabled != nil {
			config.Enabled = *req.Enabled
		}

		pageData := PageData{
			Title:       "编辑模型配置",
			Message:     "更新失败: " + err.Error(),
			MessageType: "danger",
			Config:      config,
		}
		renderTemplate(c, "form", pageData)
		return
	}

	// 清除代理缓存
	InvalidateProxyCache()

	c.Redirect(http.StatusSeeOther, "/admin?message=更新成功")
}

// 处理消息显示
func AdminWithMessage(c *gin.Context) {
	message := c.Query("message")
	messageType := c.Query("type")
	if messageType == "" {
		messageType = "success"
	}

	// 解析分页参数
	page := 1
	if pageStr := c.Query("page"); pageStr != "" {
		if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
			page = p
		}
	}

	size := 10
	modelType := c.Query("model_type")
	var enabled *int
	if enabledStr := c.Query("enabled"); enabledStr != "" {
		if e, err := strconv.Atoi(enabledStr); err == nil && (e == 0 || e == 1) {
			enabled = &e
		}
	}

	// 获取数据
	result, err := modelConfigService.ListModelConfigs(page, size, modelType, enabled)
	if err != nil {
		result = &models.ModelConfigListResponse{
			Total: 0,
			List:  []models.ModelConfig{},
			Page:  page,
			Size:  size,
		}
	}

	// 计算总页数
	totalPages := int(math.Ceil(float64(result.Total) / float64(size)))

	// 构建页面数据
	pageData := PageData{
		Title:       "模型配置管理",
		Message:     message,
		MessageType: messageType,
		Data:        result,
		Filters: FilterData{
			ModelType: modelType,
			Enabled:   c.Query("enabled"),
		},
		TotalPages: totalPages,
		PageRange:  generatePageRange(page, totalPages),
	}

	renderTemplate(c, "list", pageData)
}
